import { useEffect, useState } from 'react';

import { Button, Space, Form, Row, Col, Input, Table, Select, Popconfirm } from 'antd';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryUserListParams } from './services';
import { AppUserStatus, queryUserList, delUser, AppUserOrgType } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import DealRecordModal, { DealRecordModalProps } from './components/DealRecordModal'
import { jump2target } from '@/utils/common';

const AppUserPage: React.FC = () => {
  const [searchForm] = Form.useForm<QueryUserListParams>()
  const [searchParams, setSearchParams] = useState<QueryUserListParams>({
    pageNum: 1, pageSize: 10,
  })
  const appUserList = useRequest(() => queryUserList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delAppUserAsync } = useRequest(delUser, {manual: true})
  const [dealRecordModalProps, setDealRecordModalProps] = useState<DealRecordModalProps>({
    open: false
  })

  const openDetailPage = (title: string, appUserId: number) => {
    jump2target(`/normal/normalList/detail?userId=${appUserId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/normal/normalList/detail_title', title)
  }

  const onFinish = (formValues: QueryUserListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const openDealRecordModal = (record: AppUser) => {
    setDealRecordModalProps({
      open: true, userId: record.id
    })
  }

  const openEditPage = (record: AppUser) => {
    jump2target(`/normal/normalList/components/edit?type=add&from=2&id=${record.id}`, {needRefresh: true})
    sessionStorage.setItem('__/normal/normalList/components/edit_title', '手动退款')
  }

  const onDealRecordModalCancel = () => {
    setDealRecordModalProps({open: false})
  }

  const columns: ColumnsType<AppUser> = [
    {
      title: '用户头像',
      dataIndex: 'userImg',
      width: 100,
      render: val => val && <img style={{width: 40, height: 40}} src={val} />
    },
    {
      title: '用户昵称',
      width: 120,
      dataIndex: 'nickname',
    },
    {
      title: '用户手机号',
      width: 130,
      dataIndex: 'telephone',
    },
    {
      title: '注册日期',
      dataIndex: 'createTime',
      width: 180,
      render: createTime => dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    // {
    //   title: '充电量(度)',
    //   dataIndex: 'power',
    //   width: 120,
    // },
    // {
    //   title: '余额(元)',
    //   dataIndex: 'balance',
    //   width: 100,
    // },
    // {
    //   title: '是否经销商',
    //   dataIndex: 'companyStatus',
    //   width: 120,
    //   render: val => !!val ? '是经销商' : '非经销商'
    // },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: val => val && AppUserStatus[val]
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 200,
      fixed: 'right',
      render: (id: number, record) => {
        return <Space>
          <a onClick={() => openDealRecordModal(record)}>交易记录</a>
          <a onClick={() => openEditPage(record)}>手动退款</a>
          <a onClick={() => openDetailPage('用户详情', id)}>详情</a>
          <Access accessible={record.status === AppUserStatus.启用}>
            <Popconfirm
              title={`确定禁用用户: ${record.nickname} 吗?`}
              onConfirm={() => delAppUserAsync({userId: record.id, status: AppUserStatus.禁用}).then(appUserList.refresh)}
              okText="禁用"
              cancelText="取消"
            >
              <a>禁用</a>
            </Popconfirm>
          </Access>
          <Access accessible={record.status === AppUserStatus.禁用}>
            <Popconfirm
              title={`确定启用用户: ${record.nickname} 吗?`}
              onConfirm={() => delAppUserAsync({userId: record.id, status: AppUserStatus.启用}).then(appUserList.refresh)}
              okText="启用"
              cancelText="取消"
            >
              <a>启用</a>
            </Popconfirm>
          </Access>
          <Popconfirm
            title={`确定删除用户: ${record.nickname} 吗?`}
            onConfirm={() => delAppUserAsync({userId: record.id, status: 3}).then(appUserList.refresh)}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      appUserList.refresh()
    }
    window.addEventListener('refreshAppUserList', refresh)
    return () => {
      window.removeEventListener('refreshAppUserList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="form-area">
          <Form name='searchAppUserForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='手机号' name='telephone'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              {/* <Col span={6}>
                <Form.Item label='是否经销商' name='orgOw'>
                  <Select placeholder='请选择' options={enum2options(AppUserOrgType)} allowClear />
                </Form.Item>
              </Col> */}
              <Col span={6}>
                <Form.Item label='状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(AppUserStatus)} allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={appUserList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<AppUser>
          rowKey='id'
          loading={appUserList.loading}
          dataSource={appUserList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: appUserList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <DealRecordModal
        {...dealRecordModalProps}
        onCancel={onDealRecordModalCancel}
      />
    </div>
  );
};

export default AppUserPage;
